package com.home.andromo;

import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.net.URL;
import java.net.URLConnection;

import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ImageView;

public class ImageDownloader {

	public void download(String url, ImageView imageView) {
		BitmapDownloaderTask task = new BitmapDownloaderTask(imageView);
		task.execute(url);
	}
}

class BitmapDownloaderTask extends AsyncTask<String, Void, Bitmap> {
	private String url;
	private final WeakReference<ImageView> imageViewReference;

	public BitmapDownloaderTask(ImageView imageView) {
		imageViewReference = new WeakReference<ImageView>(imageView);
	}

	@Override
	// Actual download method, run in the task thread
	protected Bitmap doInBackground(String... params) {
		// params comes from the execute() call: params[0] is the url.
		Bitmap icono = downloadBitmap(params[0]);
		if (icono != null) {
			StoreByteImage(icono, 100, params[0]);
			return icono;
		}

		return null;
	}

	public static boolean StoreByteImage(Bitmap myImage, int quality,
			String nameFile) {
		

		File sdImageMainDirectory = new File("/sdcard/Andromo/icons");
		if(!sdImageMainDirectory.exists()){
		sdImageMainDirectory.mkdirs();
		}
		FileOutputStream fileOutputStream = null;

		Log.w("FILE", nameFile);

		try {

			BitmapFactory.Options options = new BitmapFactory.Options();
			// options.inSampleSize = 5;

			fileOutputStream = new FileOutputStream(
					sdImageMainDirectory.toString() + "/" + nameFile + ".jpg");

			BufferedOutputStream bos = new BufferedOutputStream(
					fileOutputStream);

			myImage.compress(CompressFormat.JPEG, quality, bos);

			bos.flush();
			bos.close();

		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return true;
	}

	private Bitmap downloadBitmap(String paquete) {

		URL yahoo;
		try {
			yahoo = new URL("https://play.google.com/store/apps/details?id="
					+ paquete);

			URLConnection yahooConnection = yahoo.openConnection();
			DataInputStream dis = new DataInputStream(
					yahooConnection.getInputStream());
			String inputLine;

			try {
				while ((inputLine = dis.readLine()) != null) {
					if (inputLine
							.indexOf("<div class=\"doc-banner-image-container\">") != -1) {
						System.out
								.println(inputLine
										.indexOf("<div class=\"doc-banner-image-container\">")
										+ "\n " + inputLine);
						int inicio = inputLine
								.indexOf("<div class=\"doc-banner-image-container\">");
						int fin = inputLine.indexOf("width=\"705\"");
						String nuevo = inputLine.substring(inicio, fin);
						String[] palabras = nuevo.split("\"");

						String URLfinal = palabras[3].substring(0,
								palabras[3].length() - 4)
								+ "w320";

						Log.w("Url Image", URLfinal);

						URL url = new URL(URLfinal);
						Bitmap bmp = BitmapFactory.decodeStream(url
								.openConnection().getInputStream());
						return bmp;
					}
				}
			} catch (NullPointerException e) {
				// TODO: handle exception
				return null;
			}

			dis.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			// e.printStackTrace();
			return null;
		}
		return null;
	}

	@Override
	// Once the image is downloaded, associates it to the imageView
	protected void onPostExecute(Bitmap bitmap) {
		if (isCancelled()) {
			bitmap = null;
		}

		if (imageViewReference != null) {
			ImageView imageView = imageViewReference.get();
			if (imageView != null) {
				if (bitmap != null) {
					imageView.setImageBitmap(bitmap);
				} else {
					imageView.setImageResource(R.drawable.app_no_image);
				}

			}
		}
	}

}
